<template>
  <el-dialog :title="title" :visible.sync="visible" width="90%" append-to-body @close="handleCancel">
    <div>
      <!-- 商品选择 -->
      <el-card style="margin-bottom:20px;">
        <div slot="header">商品选择</div>
        <el-form :inline="true" :model="productQuery" size="small" class="mb8">
          <el-form-item label="商品编码">
            <el-input v-model="productQuery.itemCode" placeholder="请输入商品编码" clearable />
          </el-form-item>
          <el-form-item label="商品名称">
            <el-input v-model="productQuery.itemName" placeholder="请输入商品名称" clearable />
          </el-form-item>
          <el-form-item label="规格信息">
            <el-input v-model="productQuery.specification" placeholder="请输入规格信息" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="getProductList">搜索</el-button>
          </el-form-item>
        </el-form>
        <vxe-table
          border
          size="small"
          header-align="center"
          :row-config="{isHover:true}"
          :checkbox-config="{range:true, highlight:true, checkField:'checked'}"
          @checkbox-change="handleProductCheckChange"
          @checkbox-all="handleProductCheckAll"
          :data="productList"
        >
          <vxe-column type="checkbox" width="60" align="center" />
          <vxe-column type="seq" width="60" align="center" title="序号" />
          <vxe-column field="itemCode" title="商品编码" align="center" />
          <vxe-column field="itemName" title="商品名称" align="center" />
          <vxe-column field="specification" title="规格信息" align="center" />
          <vxe-column field="imageUrl" title="图片(后补)" align="center">
            <template #default="{ row }">
              <img v-if="row.imageUrl" :src="row.imageUrl" alt="图片" style="height:32px;max-width:60px;object-fit:contain;" />
            </template>
          </vxe-column>
        </vxe-table>
        <div style="margin:8px 0 16px 0;display:flex;align-items:center;">
          <span>共{{productTotal}}条</span>
          <el-pagination
            style="margin-left:16px;"
            background
            layout="sizes, prev, pager, next, jumper"
            :total="productTotal"
            :page-size.sync="productQuery.pageSize"
            :current-page.sync="productQuery.pageNum"
            @size-change="getProductList"
            @current-change="getProductList"
            :page-sizes="[5,10,20,50,100]"
          />
        </div>
      </el-card>

      <!-- 平台商品选择 -->
      <el-card>
        <div slot="header">平台商品选择</div>
        <el-form :inline="true" :model="platformQuery" size="small" class="mb8">
          <el-form-item label="平台商品编码">
            <el-input v-model="platformQuery.platformProductCode" placeholder="请输入平台商品编码" clearable />
          </el-form-item>
          <el-form-item label="平台商品名称">
            <el-input v-model="platformQuery.platformProductName" placeholder="请输入平台商品名称" clearable />
          </el-form-item>
          <el-form-item label="平台规格信息">
            <el-input v-model="platformQuery.platformSpecInfo" placeholder="请输入平台规格信息" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="getPlatformProductList">搜索</el-button>
          </el-form-item>
        </el-form>
        <vxe-table
          border
          size="small"
          header-align="center"
          :row-config="{isHover:true}"
          :checkbox-config="{range:true, highlight:true, checkField:'checked'}"
          @checkbox-change="handlePlatformCheckChange"
          @checkbox-all="handlePlatformCheckAll"
          :data="platformProductList"
        >
          <vxe-column type="checkbox" width="60" align="center" />
          <vxe-column type="seq" width="60" align="center" title="序号" />
          <vxe-column field="platformProductCode" title="平台商品编码" align="center" />
          <vxe-column field="platformProductName" title="平台商品名称" align="center" />
          <vxe-column field="platformProductInfo" title="规格信息" align="center" />
          <!-- <vxe-column field="pictureUrl" title="图片" align="center">
            <template #default="{ row }">
              <img v-if="row.pictureUrl" :src="row.pictureUrl" alt="图片" style="height:32px;max-width:60px;object-fit:contain;" />
            </template>
          </vxe-column> -->
        </vxe-table>
        <div style="margin:8px 0 0 0;display:flex;align-items:center;">
          <span>共{{platformTotal}}条</span>
          <el-pagination
            style="margin-left:16px;"
            background
            layout="sizes, prev, pager, next, jumper"
            :total="platformTotal"
            :page-size.sync="platformQuery.pageSize"
            :current-page.sync="platformQuery.pageNum"
            @size-change="getPlatformProductList"
            @current-change="getPlatformProductList"
            :page-sizes="[10,20,50,100]"
          />
        </div>
      </el-card>
      
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleOk">确定</el-button>
      <el-button @click="handleCancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { listplatformProducts } from '@/api/mes/sales/platformProduct';
import { listMdItem } from '@/api/mes/md/mdItem';
import { addProductMapping, updateProductMapping } from '@/api/mes/sales/productMapping';
export default {
  name: 'AddProduct',
  props: {
    visible: Boolean,
    title: {
      type: String,
      default: '新增'
    },
    editData: {
      type: Object,
      default: null
    },
    mode: {
      type: String,
      default: 'add' // add/edit
    }
  },
  data() {
    return {
      productQuery: {
        pageNum: 1,
        pageSize: 5
      },
      productList: [],
      productTotal: 0,
      productChecked: [],
      platformQuery: {
        pageNum: 1,
        pageSize: 5
      },
      platformProductList: [],
      platformTotal: 0,
      platformChecked: []
    }
  },
  // watch: {
  //   visible(val) {
  //     if (val && this.mode === 'edit' && this.editData) {
  //       this.initEditData();
  //     } else if (val && this.mode === 'add') {
  //       this.resetAll();
  //     }
  //   }
  // },
  created() {
    this.getPlatformProductList();
    this.getProductList();
    if (this.mode === 'edit' && this.editData) {
      this.initEditData();
    } 
  },
  methods: {
    // 获取商品列表
    getProductList() {
      listMdItem(this.productQuery).then(response => {
        this.productList = response.rows;
        this.productTotal = response.total;
      });
    },
    // 获取平台商品列表
    getPlatformProductList() {
      listplatformProducts(this.platformQuery).then(response => {
        this.platformProductList = response.rows;
        this.platformTotal = response.total;
      });
    },
    // 编辑时回显数据和勾选
    initEditData() {
      console.log(JSON.stringify(this.editData), 'this.editData');
    },
    resetAll() {
      this.productQuery = {pageNum: 1, pageSize: 5 };
      this.platformQuery = {  pageNum: 1, pageSize: 5 };
      this.productList = [];
      this.platformProductList = [];
      this.productChecked = [];
      this.platformChecked = [];
    },
    handleProductCheckChange({ records }) {
      this.productChecked = records;
    },
    handleProductCheckAll({ records }) {
      this.productChecked = records;
    },
    handlePlatformCheckChange({ records }) {
      this.platformChecked = records;
    },
    handlePlatformCheckAll({ records }) {
      this.platformChecked = records;
    },
    handleOk() {
      // console.log(this.productChecked, 'productChecked');
      // console.log(this.platformChecked, 'platformChecked');
      // 构建两个数组，itemGroups:[{itemId: }]， platformMappings:[{platformProductId: }]
      if (this.productChecked.length === 0) {
        this.$message.warning('请至少选择一个商品');
        return;
      };
      if (this.platformChecked.length === 0) {
        this.$message.warning('请至少选择一个平台商品');
        return;
      };
      const itemGroups = this.productChecked.map(item => ({
        itemId: item.itemId
      }));
      const platformMappings = this.platformChecked.map(item => ({
        platformProductId: item.id
      }));
      const data = {
        itemGroups,
        platformMappings
      };
      if (this.mode === 'edit' && this.editData) {
        data.mappingId = this.editData.mappingId;
        updateProductMapping(data).then(response => {
          this.$message.success('编辑成功');
          this.$emit('ok');
        });
      }else{
        addProductMapping(data).then(response => {
          this.$message.success('新增成功');
          this.$emit('ok');
        });
      }
      
    },
    handleCancel() {
      this.$emit('cancel')
    }
  }
}
</script>

<style scoped>
.mb8 { margin-bottom: 8px; }
</style>
